In [1]:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

In [4]:
MNIST = input_data.read_data_sets("mnist", one_hot = True)


Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.
Extracting mnist/train-images-idx3-ubyte.gz
Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.
Extracting mnist/train-labels-idx1-ubyte.gz
Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.
Extracting mnist/t10k-images-idx3-ubyte.gz
Successfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.
Extracting mnist/t10k-labels-idx1-ubyte.gz

In [5]:
MNIST


Out[5]:
Datasets(train=<tensorflow.contrib.learn.python.learn.datasets.mnist.DataSet object at 0x7fe1b54b30b8>, validation=<tensorflow.contrib.learn.python.learn.datasets.mnist.DataSet object at 0x7fe1b5526a90>, test=<tensorflow.contrib.learn.python.learn.datasets.mnist.DataSet object at 0x7fe1b5526cc0>)

In [6]:
learning_rate = 0.01
batch_size = 128
n_epochs = 25

Dimensions: X pri X*W (rows: number of pictures in batch, colums:number of pixels) Y has number of rows same as batch size and columns like number of classes


In [24]:
X = tf.placeholder(tf.float32, [batch_size, 784])
Y = tf.placeholder(tf.float32, [batch_size, 10])

In [25]:
# Create variables for weights and biasses
# Size of W is for X*W rows: number of classes, columns:number of pixels
# Bias is each for every class
W = tf.Variable(tf.random_normal(shape=[784, 10], stddev=0.01), name="weights")
b = tf.Variable(tf.zeros([1, 10]), name="bias")

In [26]:
logits = tf.matmul(X, W) + b

In [27]:
entropy = tf.nn.softmax_cross_entropy_with_logits(labels=Y, logits=logits)
loss = tf.reduce_mean(entropy) # Mean for all samples in minibatch

In [28]:
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(loss)

In [29]:
init = tf.global_variables_initializer()

In [41]:
with tf.Session() as sess:
    sess.run(init)
    
    n_batches = int(MNIST.train.num_examples/batch_size)
    total_correct = 0
    for i in range(n_epochs):
        for _ in range(n_batches):
            X_batch, Y_batch = MNIST.train.next_batch(batch_size)
            _, loss_batch, logits_batch = sess.run([optimizer, loss, logits], feed_dict={X: X_batch, Y: Y_batch})
            preds = tf.nn.softmax(logits_batch)
            correct_preds = tf.equal(tf.argmax(preds, 1), tf.argmax(Y_batch, 1))
            accuracy = tf.reduce_sum(tf.cast(correct_preds, tf.float32))
            total_correct += sess.run(accuracy)
            
            # loss_value = loss.eval(feed_dict={Y: Y_batch})
            
        print('Epoch number ', i+1, ' has Loss:', loss_batch, ' Acuracy: ', total_correct)


Epoch number  1  has Loss: 0.812474  Acuracy:  42363.0
Epoch number  2  has Loss: 0.740915  Acuracy:  88821.0
Epoch number  3  has Loss: 0.592127  Acuracy:  136120.0
Epoch number  4  has Loss: 0.486201  Acuracy:  183864.0
Epoch number  5  has Loss: 0.478784  Acuracy:  231957.0
Epoch number  6  has Loss: 0.419299  Acuracy:  280304.0
Epoch number  7  has Loss: 0.368642  Acuracy:  328809.0
Epoch number  8  has Loss: 0.371604  Acuracy:  377452.0
Epoch number  9  has Loss: 0.464372  Acuracy:  426223.0
Epoch number  10  has Loss: 0.409481  Acuracy:  475119.0
Epoch number  11  has Loss: 0.435832  Acuracy:  524099.0
Epoch number  12  has Loss: 0.524812  Acuracy:  573200.0
Epoch number  13  has Loss: 0.385834  Acuracy:  622346.0
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-41-4f3c2d882930> in <module>()
     11             correct_preds = tf.equal(tf.argmax(preds, 1), tf.argmax(Y_batch, 1))
     12             accuracy = tf.reduce_sum(tf.cast(correct_preds, tf.float32))
---> 13             total_correct += sess.run(accuracy)
     14 
     15             # loss_value = loss.eval(feed_dict={Y: Y_batch})

/home/scapogo/Projects/DeepLearning/venv/lib/python3.5/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    765     try:
    766       result = self._run(None, fetches, feed_dict, options_ptr,
--> 767                          run_metadata_ptr)
    768       if run_metadata:
    769         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/home/scapogo/Projects/DeepLearning/venv/lib/python3.5/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    963     if final_fetches or final_targets:
    964       results = self._do_run(handle, final_targets, final_fetches,
--> 965                              feed_dict_string, options, run_metadata)
    966     else:
    967       results = []

/home/scapogo/Projects/DeepLearning/venv/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1013     if handle is None:
   1014       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1015                            target_list, options, run_metadata)
   1016     else:
   1017       return self._do_call(_prun_fn, self._session, handle, feed_dict,

/home/scapogo/Projects/DeepLearning/venv/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1020   def _do_call(self, fn, *args):
   1021     try:
-> 1022       return fn(*args)
   1023     except errors.OpError as e:
   1024       message = compat.as_text(e.message)

/home/scapogo/Projects/DeepLearning/venv/lib/python3.5/site-packages/tensorflow/python/client/session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
    998                 run_metadata):
    999       # Ensure any changes to the graph are reflected in the runtime.
-> 1000       self._extend_graph()
   1001       with errors.raise_exception_on_not_ok_status() as status:
   1002         return tf_session.TF_Run(session, options,

/home/scapogo/Projects/DeepLearning/venv/lib/python3.5/site-packages/tensorflow/python/client/session.py in _extend_graph(self)
   1047         with errors.raise_exception_on_not_ok_status() as status:
   1048           tf_session.TF_ExtendGraph(
-> 1049               self._session, graph_def.SerializeToString(), status)
   1050         self._opened = True
   1051 

KeyboardInterrupt: 

In [ ]: